package com.neuedu.web.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auth 金山老师
 * title:   书籍代码
 * creatime: 2022-10-18 8:57
 * 描述 :
 */
public class FirstServlet extends HttpServlet {


    //1 实例化对象
    public FirstServlet( ) {
        System.out.println("FirstServlet.FirstServlet 实例化对象");
    }



    // @Override
    // public void init(ServletConfig config) throws ServletException {
    //     config.getInitParameter("username")
    // }

    //2 初始化Servlet
    @Override
    public void init( ) throws ServletException {
        String username =  getInitParameter("username");
        String password =  getInitParameter("password");
        String url  =  getInitParameter("url");

        System.out.println("username = " + username);
        System.out.println("password = " + password);
        System.out.println("url = " + url);
        System.out.println("初始化的业务逻辑.....");
    }


    //
    /**
     *
     *
     * 3 service (反复执行的方法) {
     *      doGet
     *      doPost
     *
     *
     * }
     *
     *
     * 调用doget
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("FirstServlet.doGet");
        this.doPost(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //处理业务逻辑
        System.out.println("FirstServlet.doPost");
        System.out.println(this);
        //从响应对象中获取输出
        ServletOutputStream out = response.getOutputStream();

        //向客户端输出内容
        out.print("hello Servlet ");
        //清空缓存
        out.flush();
        //关闭流
        out.close();
    }



    //4 容器销毁的时候 会通知Servlet 执行destory方法 【有时不一定能100% 的执行】
    @Override
    public void destroy( ) {
        System.out.println("FirstServlet.destroy 销毁资源");
    }
}
